<?php

namespace App\Models;

use App\Http\Controllers\PdfController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛作品数据库关联表
 * Class ArticleModel
 * @package app\common\model
 */
class CompetiteActivityWorksDatabase extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'competite_activity_works_database';


  


    /**
     * 获取作品数据库数量
     * @param dabatase_id  数据库id
     */
    public function databaseNumber($dabatase_id)
    {
        return $this->where('database_id', $dabatase_id)->count();
    }


    /** 
     * 收录作品
     * @param database_id int 数据库id
     * @param ebook_ids int 作品id 多个逗号拼接
     * @param ebook_ids int 电子书id 多个逗号拼接   works_ids 与 ebook_ids 二选一，一次只能收录一种类型，但不能同时为空
     */
    public function recordAdd($data)
    {
        if (!empty($data['works_ids'])) {
            $ids =  $data['works_ids'];
            $type =  1;
            $field =  'works_id';
        } else {
            $ids =  $data['ebook_ids'];
            $type =  2;
            $field =  'ebook_id';
        }

        $ids = explode(',', $ids);
        foreach ($ids as $key => $val) {
            $is_exists = $this->where('database_id', $data['database_id'])->where('type', $type)->where($field, $val)->first();
            if (empty($is_exists)) {
                $obj = new self();
                $obj->database_id = $data['database_id'];
                $obj->$field = $val;
                $obj->type = $type;
                $obj->save();
            }
        }
        return true;
    }

    /**
     * 删除收录的产品
     * @param id  收录的id
     */
    public function recordDel($id)
    {
        $id = !is_array($id) ? explode(',', $id) : $id;
        return $this->whereIn('id', $id)->delete();
    }



    /**
     * 列表
     * @param database_id int 数据库id
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(作品数据库名称)
     * @param start_time datetime 创建时间(开始)
     * @param end_time datetime 创建时间(截止)
     * @param type datetime 类型  1 作品  2 电子书
     */
    public function lists($database_id, $keywords, $type, $start_time, $end_time, $limit = 10)
    {
        // DB::enableQueryLog();
        $res = $this->from($this->getTable() . ' as wd')
            ->select(
                'wd.id',
                'wd.type',
                'wd.create_time',
                'wd.database_id',
                'wd.works_id',
                'wd.ebook_id',
                'wd.sort',
                'w.title',
                'w.username',
                'w.cover',
                'e.name',
                'e.img',
                'e.author'
            )
            ->leftjoin('competite_activity_works as w', function ($query) {
                $query->on('wd.works_id', '=', 'w.id')->where('wd.type', 1); //类型为1 ，才满足当前情况

            })->leftjoin('competite_activity_ebook as e', function ($query) {
                $query->on('wd.ebook_id', '=', 'e.id')->where('wd.type', 2)->where('e.is_play', 1); //类型为2 ，才满足当前情况
            })->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('e.name', 'like', '%' . $keywords . '%')->orWhere('w.title', 'like', '%' . $keywords . '%');
                }
            })->where(function ($query) use ($type, $start_time, $end_time) {
                if ($type) {
                    $query->where('wd.type', $type);
                }
                if ($start_time && $end_time) {
                    $query->whereBetween('wd.create_time', [$start_time, $end_time]);
                }
            })->where('wd.database_id', $database_id)
            ->orderBy('wd.sort')
            ->paginate($limit)
            ->toArray();
        foreach ($res['data'] as $key => $val) {
            if ($val['type'] == 1) {
                $res['data'][$key]['name'] = $val['title'];
                $res['data'][$key]['author'] = $val['username'];
                $res['data'][$key]['img'] = $val['cover'];
            }
            unset($res['data'][$key]['title'], $res['data'][$key]['username'], $res['data'][$key]['cover']);
        }

        //  dump(DB::getQueryLog());
        return $res;
    }

    /**
     * 获取当前数据库数据量
     * @param database_id 数据库id
     */
    public function databaseWorksNumber($database_id = null)
    {
        return $this->where(function ($query) use ($database_id) {
            if ($database_id) {
                $database_id = !is_array($database_id) ? explode(',', $database_id) : $database_id;
                $query->whereIn('database_id', $database_id);
            }
        })->count();
    }
    /**
     * 获取当前数据库下的作品id
     * @param database_id 数据库id
     * @param type 类型  1 作品id  2 电子书id 
     */
    public function databaseWorksId($database_id = null, $type = 1)
    {
        $field_name = $type == 1 ? 'works_id' : 'ebook_id';
        return $this->where(function ($query) use ($database_id) {
            if ($database_id) {
                $database_id = !is_array($database_id) ? explode(',', $database_id) : $database_id;
                $query->whereIn('database_id', $database_id);
            }
        })->whereNotNull($field_name)->pluck($field_name)
        ->toArray();
    }

}
